const { Controller } = require('dx-router-admin');

module.exports = class User extends Controller {
	constructor(ctx) {
		super(ctx);
	}
	//重置密码
	async resetpwd() {
		let password = this.$dx.request.post('password');
		if (!password) {
			return this.$dx.fail('密码不能为空！');
		}
	}
	//设置头像
	async setAvatar({ avatar }) {
		if (!avatar) {
			return this.$dx.fail('参数错误');
		}
	}
	//获取用户信息
	async getUserInfo() {
		const userInfo = await this.currentService.getCurrentUserInfo();
		return this.$dx.success('获取成功', userInfo);
	}
	//编辑信息
	async edit({ nickname, avatar, mobile, email, gender, password }) {
		// 有值就更新
		const data = {
			_id: this.$dx.auth.uid,
		};
		if (nickname) {
			data.nickname = nickname;
		}
		if (avatar) {
			data.avatar = avatar;
		}
		if (mobile) {
			if (!this.$dx.utils.isMobile(mobile)) {
				return this.$dx.fail('手机号码格式错误');
			}
			data.mobile = mobile;
		}
		if (email) {
			data.email = email;
		}
		if (gender == 1 || gender == 2) {
			data.gender = gender;
		}
		// 如果密码存在，修改密码
		if (password) {
			let { passwordHash, version } = this.currentService.getPasswordExtMethod(password);
			data.password = passwordHash;
			data.password_secret_version = version;
		}
		if(Object.keys(data).length === 1){
			return this.$dx.fail('参数错误');
		}
		// 更新
		let status = await this.currentService.save(data);
		if (status) {
			const userInfo = await this.currentService.getCurrentUserInfo();
			return this.$dx.success('操作成功', userInfo);
		}
		return this.$dx.fail('操作失败');
	}
	// 设置推送cid
	async setPushCid({pushClientId}){
		if(!pushClientId){
			return this.$dx.fail('参数错误');
		}
		await this.$dx.service.device.saveDevice(pushClientId);
		return this.$dx.success('操作成功');
	}
};
